package service;

import com.alibaba.fastjson.JSONObject;
import entity.LogCenterBody;
import entity.LogCenterModel;
import entity.LogCenterResponse;
import entity.RowItem;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import utils.HttpClientUtil;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * @author weijianyu
 */
@Service
public class YzmCheckService {
    private static final Logger logger = LogManager.getLogger(YzmCheckService.class);
    private static final int ZERO = 0;
    private static final String ENDSTR = " +0800";
    private static final String URL = "http://logcenter.data.sankuai.com/logcenter/search";
    private static final String SUCCESS = "0";
    private static final String EOF = "\r\n";
    private static final String SPLIT = ",";

    private static final String DEFAULT_LOSE_TIME = "-06-30 00:00:00";

    public void loadYzm(String starTime, String endTime, int from, int limit) {
        LogCenterResponse response = JSONObject.parseObject(
                HttpClientUtil.post(URL, builtBody(starTime, endTime, from, limit)), LogCenterResponse.class);
        if (response == null || !StringUtils.equals(response.getErrorCode(), SUCCESS) || StringUtils.isNotBlank(response.getErrorMsg())) {
            return;
        }
        decodeData(response.getData());
    }

    private LogCenterBody builtBody(String starTime, String endTime, int from, int limit) {
        LogCenterBody body = LogCenterBody.builtDefaultBody();
        body.setFrom(from);
        body.setSize(limit);
        LogCenterBody.EsTimestamp esTimestamp = body.getQuery().getBool().getFilters().get(ZERO).getRange().getEsTimestamp();
        esTimestamp.setGte(starTime + ENDSTR);
        esTimestamp.setLte(endTime + ENDSTR);
        return body;
    }

    private void decodeData(LogCenterModel logModel) {
        for (RowItem item : logModel.getRows()) {
            if (item == null || StringUtils.isEmpty(item.getMessage())) {
                continue;
            }
            try {
                String fileName = getFileName(item.getMessage());
                String fileData = getFileData(item.getMessage());
                outToFile(fileName, fileData);
            } catch (Exception e) {
                continue;
            }
        }
    }

    private String getFileName(String message) {
        String result = "result:";
        return message.substring(message.indexOf(result) + result.length(), message.indexOf(EOF));
    }

    private String getFileData(String message) {
        String originalCode = "originalCode:";
        return message.substring(message.indexOf(originalCode) + originalCode.length(), message.lastIndexOf(SPLIT));
    }

    private void outToFile(String fileName, String fileData) {
        String path = "/Users/weijianyu/yzm/18/" + fileName + "-" + System.currentTimeMillis()+".png";
        try {
            FileOutputStream outputStream = new FileOutputStream(path);
            byte[] datas = Base64.decodeBase64(fileData);
            outputStream.write(datas);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error("file out put error", e);
        }
    }

    public static Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    public static Date getnowEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    public static Date getYesterdayStartTime() {
        DateTime yesterday = new DateTime().minusDays(1);
        Calendar yesterdayDate = Calendar.getInstance();
        yesterdayDate.setTime(yesterday.toDate());
        yesterdayDate.set(Calendar.HOUR_OF_DAY, 0);
        yesterdayDate.set(Calendar.MINUTE, 0);
        yesterdayDate.set(Calendar.SECOND, 0);
        yesterdayDate.set(Calendar.MILLISECOND, 0);
        return yesterdayDate.getTime();
    }

    public static Date getYesterdayStartTime1() {
        Calendar yesterdayDate = Calendar.getInstance();
        yesterdayDate.add(Calendar.DATE, -1);
        yesterdayDate.set(Calendar.HOUR_OF_DAY, 0);
        yesterdayDate.set(Calendar.MINUTE, 0);
        yesterdayDate.set(Calendar.SECOND, 0);
        yesterdayDate.set(Calendar.MILLISECOND, 0);
        return yesterdayDate.getTime();
    }

    public static void main(String[] args) {
//        YzmCheckService service = new YzmCheckService();
//        String startTime = "2018/04/23 06:00:00";
//        String endTime = "2018/04/23 15:00:00";
//        service.loadYzm(startTime, endTime, 0, 400);

        System.out.println(getYesterdayStartTime1().getTime());
        System.out.println(getYesterdayStartTime().getTime());

    }
}
